import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useUserStore } from "./user";
import { addCartApi, getNewCartListApi, deleteCartApi } from "@/api/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    //存储数据
    const cartList = ref([]);
    //添加商品到购物车
    const addCart = async (goods) => {
      const { skuId, count } = goods;
      if (isLogin.value) {
        await addCartApi(skuId, count);
        const res = await getNewCartListApi();
        console.log(res);
        cartList.value = res.result;
      } else {
        //判断商品是否已经在购物车中
        const index = cartList.value.find((item) => item.skuId === goods.skuId);
        if (index) {
          index.count += 1;
        } else {
          cartList.value.push(goods);
        }
      }
    };
    //删除购物车商品
    const deleteCart = async (skuId) => {
      if (isLogin.value) {
        await deleteCartApi([skuId]);
        const res = await getNewCartListApi();
        cartList.value = res.result;
      } else {
        const idx = cartList.value.findIndex((item) => item.skuId === skuId);
        cartList.value.splice(idx, 1);
      }
    };
    //删除小layer购物车商品
    // const deleteCart = (skuId) => {
    //   const newList = cartList.value.filter((item) => item.skuId !== skuId);
    //   cartList.value = newList;
    // };
    //计算总数量
    const totalCount = computed(() => cartList.value.reduce((pre, cur) => pre + cur.count, 0));
    //计算总价
    const totalPrice = computed(() =>
      cartList.value.reduce((pre, cur) => pre + cur.price * cur.count, 0)
    );
    //单选商品
    const singleChange = (skuId, selected) => {
      cartList.value.find((item) => item.skuId === skuId).selected = selected;
    };
    //全选商品
    const allChange = (selected) => {
      cartList.value.forEach((item) => (item.selected = selected));
    };
    //全选按钮状态
    const allSelected = computed(() => {
      return cartList.value.every((item) => item.selected);
    });
    //计算选中商品的数量
    const selectedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected === true)
        .reduce((pre, cur) => pre + cur.count, 0);
    });
    //计算选中商品的总价
    const selectedPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected === true)
        .reduce((pre, cur) => pre + cur.price * cur.count, 0);
    });
    return {
      cartList,
      addCart,
      deleteCart,
      totalCount,
      totalPrice,
      singleChange,
      allChange,
      allSelected,
      selectedCount,
      selectedPrice,
    };
  },
  {
    persist: true,
  }
);
